<template>
	<div class="app-container">
		<div v-if="showBlock">
			<!-- 搜索 -->
      <div class="filter-container tw-filter">
        <el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-edit" v-has="$store.state.user.btn_common+'add'" @click="handleAdd()">添加</el-button>
        <el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-delete" v-has="$store.state.user.btn_common+'del'" @click="handleDelete()">批量删除</el-button>

        <el-input v-model="queryList.name" placeholder="请输入字典名称" class="filter-item tw-filter-input" clearable/>
        <el-input v-model="queryList.ident" placeholder="请输入字典标识" class="filter-item tw-filter-input" clearable/>
        <el-select v-model="queryList.state" class="filter-item tw-filter-input" placeholder="请选择状态" clearable>
        	<el-option key="" label="全部状态" value="" />
        	<el-option key="1" label="启用" value="1" />
        	<el-option key="0" label="禁用" value="0" />
        </el-select>
        <el-button v-waves class="filter-item tw-filter-button" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      </div>

			<!-- 表格内容展示 -->
			<el-table
			  ref="multipleTable"
			  :key="tableKey"
			  v-loading="listLoading"
			  :data="tableList"
			  @selection-change="handleSelectionChange"
			  border fit highlight-current-row style="width: 100%;"
			>
				<el-table-column type="selection" width="50" />
				<el-table-column label="排序" prop="sort_id" align="center" width="80" v-has="$store.state.user.btn_common+'edit'">
					<template slot-scope="{row}">
						<el-input v-model="row.sort_id" class="edit-input" size="small" @change="updateSort(row.id,row.sort_id)" />
					</template>
				</el-table-column>
				<el-table-column label="字典名称" prop="name" align="left" />
				<el-table-column label="字典标识" prop="ident" align="left" />
				<el-table-column label="备注" prop="remark" align="left" width="250" />
				<el-table-column label="状态" align="center">
					<template slot-scope="{row}">
						<span v-if="row.state == 1">启用</span>
						<span v-else>禁用</span>
					</template>
				</el-table-column>

				<el-table-column label="操作" width="320px" align="center" class-name="small-padding fixed-width">
					<template slot-scope="{row}">
						<el-button size="mini" v-has="$store.state.user.btn_common+'list_item'" @click="handleItemShow(row.id)">管理字典内容</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'edit'" @click="handleEdit(row.id)">编辑</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'upshow'" v-if="row.state" @click="handleUpshow(row.id)">禁用</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'show'" v-else @click="handleShow(row.id)">启用</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'del'" @click="handleDelete(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="isPage && listTotal > 0" :total="listTotal" :page.sync="queryList.curpage" :limit.sync="queryList.page" @pagination="getList" />

			<!-- 添加/编辑 -->
			<el-dialog width="40%" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
			  <el-form label-position="right" label-width="120px" ref="dataForm" :rules="rules" :model="form">
					<el-form-item label="字典名称" prop="name" filter="false">
						<el-input v-model="form.name" placeholder="请输入字典名称" />
					</el-form-item>
					<el-form-item label="字典标识" prop="ident" filter="false">
						<el-input v-model="form.ident" placeholder="请输入字典标识" />
						<p class="tw-tip-text">必须唯一，只能包含字母、数字、下划线</p>
					</el-form-item>
					<el-form-item label="备注" prop="remark" filter="false">
						<el-input type="textarea" :rows="3" v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
					<el-form-item label="状态" prop="state">
						<el-radio-group v-model="form.state">
							<el-radio :label="1">启用</el-radio>
							<el-radio :label="0">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="排序" prop="sort_id">
						<el-input v-model="form.sort_id" placeholder="请输入排序" filter="false" />
					</el-form-item>
				</el-form>

				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogStatus==='create'?createData():updateData()">保存</el-button>
					<el-button @click="dialogFormVisible = false">取消</el-button>
				</div>
			</el-dialog>
		</div>

		<!-- 字典内容管理 -->
		<div v-if="showBlock1">
			<!-- 过滤器容器 -->
			<div class="filter-container tw-filter">
				<el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-arrow-left" @click="handleReturn">返回</el-button>
				<el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-edit"v-has="$store.state.user.btn_common+'add_item'" @click="handleAdd1">添加</el-button>
				<el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-delete" v-has="$store.state.user.btn_common+'del_item'" @click="handleDelete1()">批量删除</el-button>

				<el-input v-model="queryList1.key" placeholder="请输入字典项编号" class="filter-item tw-filter-input" />
				<el-input v-model="queryList1.value" placeholder="请输入字典项值" class="filter-item tw-filter-input" />
				<el-select v-model="queryList1.is_default" class="filter-item tw-filter-input" placeholder="请选择是否默认" clearable>
					<el-option key="" label="全部" value="" />
					<el-option key="1" label="是" value="1" />
					<el-option key="0" label="否" value="0" />
				</el-select>
				<el-select v-model="queryList1.state" class="filter-item tw-filter-input" placeholder="请选择状态" clearable>
					<el-option key="" label="全部状态" value="" />
					<el-option key="1" label="启用" value="1" />
					<el-option key="0" label="禁用" value="0" />
				</el-select>

				<el-button v-waves class="filter-item tw-filter-button" size="medium" icon="el-icon-search" @click="handleFilter1">搜索</el-button>
			</div>

			<!-- 表格内容展示 -->
			<el-table
        ref="multipleTable"
        :key="tableKey1"
        v-loading="listLoading1"
        :data="tableList1"
        border fit highlight-current-row style="width: 100%;"
        @selection-change="handleSelectionChange1"
      >
				<el-table-column type="selection" width="50" />
				<el-table-column label="排序" prop="sort_id" align="center" width="80" v-has="$store.state.user.btn_common+'edit_item'">
					<template slot-scope="{row}">
						<el-input v-model="row.sort_id" class="edit-input" size="small"
							@change="updateSort1(row.id,row.sort_id)" />
					</template>
				</el-table-column>
				<el-table-column label="字典项编号" prop="key" align="left" width="150" />
				<el-table-column label="字典项值" prop="value" align="left" width="400" />
        <!-- <el-table-column label="是否企业显示" align="center">
        	<template slot-scope="{row}">
        		<span v-if="row.is_company == 1">是</span>
        		<span v-else>否</span>
        	</template>
        </el-table-column> -->
        <el-table-column label="是否默认" align="center">
        	<template slot-scope="{row}">
        		<span v-if="row.is_default == 1">是</span>
        		<span v-else>否</span>
        	</template>
        </el-table-column>
				<el-table-column label="状态" align="center">
					<template slot-scope="{row}">
						<span v-if="row.state == 1">启用</span>
						<span v-else>禁用</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="220" align="center" class-name="small-padding fixed-width">
					<template slot-scope="{row}">
						<el-button size="mini" v-has="$store.state.user.btn_common+'edit_item'" @click="handleEdit1(row.id)">编辑</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'upshow_item'" v-if="row.state" @click="handleUpshow1(row.id)">禁用</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'show_item'" v-else @click="handleShow1(row.id)">启用</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'del_item'" @click="handleDelete1(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="isPage1 && listTotal1 > queryList1.page" :total="listTotal1" :page.sync="queryList1.curpage" :limit.sync="queryList1.page" @pagination="getItemList" />

			<!-- 添加/编辑 -->
			<el-dialog width="40%" :title="textMap1[dialogStatus1]" :visible.sync="dialogFormVisible1">
			  <el-form label-position="right" label-width="120px" ref="dataForm1" :rules="rules1" :model="form1">
          <el-form-item label="字典项值" prop="value" filter="false">
          	<el-input v-model="form1.value" placeholder="请输入字典项值" />
          	<p class="tw-tip-text">必须唯一</p>
          </el-form-item>
					<el-form-item label="字典项编号" prop="key" filter="false">
						<el-input v-model="form1.key" placeholder="请输入字典项编号" />
						<p class="tw-tip-text">必须唯一，只能输入整数</p>
					</el-form-item>
          
          <!-- <el-form-item label="是否企业" prop="is_company">
          	<el-radio-group v-model="form1.is_company">
          		<el-radio :label="1">是</el-radio>
          		<el-radio :label="0">否</el-radio>
          	</el-radio-group>
          </el-form-item> -->
          <el-form-item label="是否默认" prop="is_default">
          	<el-radio-group v-model="form1.is_default">
          		<el-radio :label="1">是</el-radio>
          		<el-radio :label="0">否</el-radio>
          	</el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="state">
          	<el-radio-group v-model="form1.state">
          		<el-radio :label="1">启用</el-radio>
          		<el-radio :label="0">禁用</el-radio>
          	</el-radio-group>
          </el-form-item>
          <el-form-item label="排序" prop="sort_id">
          	<el-input v-model="form1.sort_id" placeholder="请输入排序" filter="false" />
          </el-form-item>
        </el-form>

				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogStatus1==='create'?createData1():updateData1()">保存</el-button>
					<el-button @click="dialogFormVisible1 = false">取消</el-button>
				</div>
			</el-dialog>
		</div>
	</div>
</template>

<script>
	import Pagination from '@/components/Pagination' // 基于el分页的二次封装
	import waves from '@/directive/waves' // waves directive

	export default {
		components: { Pagination},
		directives: { waves },
		data() {
			return {
				// 数据列表
				listLoading: true,
				tableKey: 0,
				listTotal: 0,
				isPage: false,
				tableList: [],
				multipleSelection: [],//多选数据
				// 添加/编辑弹窗
				dialogFormVisible: false,
				dialogStatus: '',
				textMap: {
					update: '编辑',
					create: '添加'
				},
				// 搜索数据
				queryList: {
					page: this.$store.state.settings.page, // 每页显示数量
					curpage: 1, // 当前页码
          name: '', //字典名称
					ident: '', // 字典标识
					state: null //状态：0-禁用 1-启用
				},
        //键字段
        keyName: 'id',
        apiPath: 'project.dictionary',

				// 表单数据
				form: {
					id: 0, //ID
					name: '', // 字典名称
					ident: '', // 字典标识
					remark: '', //备注
					state: 1, //状态：0-禁用 1-启用
					sort_id: 255 // 排序
				},
				// 重置数据
				formReset: {
					id: 0, //ID
					name: '', // 字典名称
					ident: '', // 字典标识
					remark: '', //备注
					state: 1, //状态：0-禁用 1-启用
					sort_id: 255 // 排序
				},
				// 验证
				rules: {
					name: [{ required: true, message: '请输入字典名称！', trigger: 'change' }],
					ident: [{ required: true, message: '请输入字典标识！', trigger: 'change' }],
				},


        //字典管理
        showBlock: true,
        showBlock1: false,
        relevanceID: 'dic_id', //关联ID
				dic_id: '', //父表ID

        /*字典项*/
        // 数据列表
        listLoading1: true,
        tableKey1: 1,
        listTotal1: 0,
        isPage1: false,
        tableList1: [],
        multipleSelection1: [],//多选数据
        // 添加/编辑弹窗
        dialogFormVisible1: false,
        dialogStatus1: '',
        textMap1: {
        	update: '编辑',
        	create: '添加'
        },
        // 搜索数据
        queryList1: {
        	page: this.$store.state.settings.page, // 每页显示数量
        	curpage: 1, // 当前页码
          dic_id: 0,
        	key: '', //字典项编号
        	value: '', //字典项值
        	is_default: null, //是否默认
        	state: null, //状态：0-禁用 1-启用
        },
        //键字段
        keyName1: 'id',
        apiPath1: 'project.dictionaryitem',

        // 表单数据
        form1: {
          id: '',
        	dic_id: '', // 字典ID
        	key: '', //字典项编号
					value: '', //字典项值
          is_company: 1, //是否企业
          is_default: 0, //是否默认
        	state: 1, //状态：0-禁用 1-启用
        	sort_id: 255, // 排序
        },
        // 重置数据
        formReset1: {
          id: '',
          dic_id: '', // 字典ID
          key: '', //字典项编号
          value: '', //字典项值
          is_company: 1, //是否企业
          is_default: 0, //是否默认
          state: 1, //状态：0-禁用 1-启用
          sort_id: 255, // 排序
        },
        // 验证
        rules1: {
        	key: [{ required: true, message: '请输入字典项编号！', trigger: 'change' }],
        	value: [{ required: true, message: '请输入字典项值！', trigger: 'change' }],
        },
			}
		},
		created() {
			//获取字典列表
			this.getList()
		},

		methods: {
/*******************************公共方法******************************/
      // 搜索
      handleFilter() {
      	this.queryList.curpage = 1
      	this.tableList = []
        this.listTotal = 0
      	this.getList()
      },
      // 列表选择
      handleSelectionChange(val) {
      	this.multipleSelection = val
      },
      // 重置form
      resetForm() {
      	this.form = JSON.parse(JSON.stringify(this.formReset))
      },
			// 获取数据列表
			getList() {
				this.listLoading = true
				this.$api.fetchList(this.queryList, this.apiPath).then(response => {
					this.tableList = response.list
					this.listTotal = response.list_count
					this.isPage = response.is_page
          this.listLoading = false
				})
			},
			// 添加
			handleAdd() {
			  this.resetForm()
			  this.dialogStatus = 'create'
			  this.dialogFormVisible = true
			  this.$nextTick(() => {
			    this.$refs['dataForm'].clearValidate()
			  })
			},
			// 编辑
			handleEdit(id = 0) {
			  this.resetForm()
			  // 获取详情
			  this.$api.getDetail({ id: id }, this.apiPath).then(response => {
          //数据处理
          for(let key in this.form){
            if(response.detail.hasOwnProperty(key)){
              this.form[key] = response.detail[key]
            }
          }
			  })
			  this.dialogStatus = 'update'
			  this.dialogFormVisible = true
			  this.$nextTick(() => {
			    this.$refs['dataForm'].clearValidate();
			  })
			},
      // 添加-数据提交
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$api.add(this.form, this.apiPath).then(() => {
              // 重新获取列表
              this.queryList.curpage = 1
              this.tableList = []
              this.getList()

              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 编辑-数据提交
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$api.edit(this.form, this.apiPath).then(response => {
              // 重新获取列表
              this.getList()

              this.dialogFormVisible = false
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 删除
      handleDelete(id = 0) {
        let current = this
        let id_str = ''
        if (!id) {
          // 多选
          if (!this.multipleSelection.length) {
            this.$message({
              message: '请选择删除的条目！',
              type: 'warning'
            })
            return false
          }
          // 数据处理
          this.multipleSelection.forEach(item => {
            id_str += item[current.keyName] + ','
          })
        } else {
          id_str = id
        }

        // 提交数据
        this.$confirm('确认删除数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.del({ id_str: id_str }, this.apiPath).then(response => {
            // 重新获取列表
            this.getList()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          })
        })
      },
			// 排序
			updateSort(id = 0, sort = '') {
				this.$api.editSort({
					id: id,
					sort: sort
				}, this.apiPath).then(response => {
					this.$message({
						message: '排序成功',
						type: 'success'
					})
				})
			},
			//启用
			handleShow(id = 0) {
				this.$confirm('确认启用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.show({ id_str: id }, this.apiPath).then(response => {
						// 重新获取列表
						this.getList()
						this.$message({
							message: '启用成功',
							type: 'success'
						})
					})
				})
			},
			//禁用
			handleUpshow(id = 0) {
				this.$confirm('确认禁用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.upshow({ id_str: id }, this.apiPath).then(response => {
						// 重新获取列表
						this.getList()
						this.$message({
							message: '禁用成功',
							type: 'success'
						})
					})
				})
			},
/*******************************公共方法END******************************/

			/*管理字典*/
      //点击管理字典
      handleItemShow(id=0) {
        this.queryList1[this.relevanceID] = id;
        this[this.relevanceID] = id;
        this.showBlock = false;
        this.showBlock1 = true;
        //获取列表
        this.getItemList();
      },
      //点击返回字典位
      handleReturn() {
        this[this.relevanceID] = 0;
        this.queryList1[this.relevanceID] = 0;
        this.showBlock = true;
        this.showBlock1 = false;
      },
/*******************************公共方法1******************************/
      // 搜索
      handleFilter1() {
      	this.queryList1.curpage = 1
      	this.tableList1 = []
        this.listTotal1 = 0
      	this.getItemList()
      },
      // 列表选择
      handleSelectionChange1(val) {
      	this.multipleSelection1 = val
      },
      // 重置form
      resetForm1() {
      	this.form1 = JSON.parse(JSON.stringify(this.formReset1))
      },
			// 获取数据列表
			getItemList() {
				this.listLoading1 = true
				this.$api.fetchList(this.queryList1, this.apiPath1).then(response => {
					this.tableList1 = response.list
					this.listTotal1 = response.list_count
					this.isPage1 = response.is_page
          this.listLoading1 = false
				})
			},
			// 添加
			handleAdd1() {
			  this.resetForm1()
			  this.dialogStatus1 = 'create'
			  this.dialogFormVisible1 = true
			  this.$nextTick(() => {
			    this.$refs['dataForm1'].clearValidate()
			  })
			},
			// 编辑
			handleEdit1(id = 0) {
			  this.resetForm1()
			  // 获取详情
			  this.$api.getDetail({ id: id }, this.apiPath1).then(response => {
          //数据处理
          for(let key in this.form1){
            if(response.detail.hasOwnProperty(key)){
              this.form1[key] = response.detail[key]
            }
          }
			  })
			  this.dialogStatus1 = 'update'
			  this.dialogFormVisible1 = true
			  this.$nextTick(() => {
			    this.$refs['dataForm1'].clearValidate();
			  })
			},
      // 添加-数据提交
      createData1() {
        this.$refs['dataForm1'].validate((valid) => {
          if (valid) {
            this.form1[this.relevanceID] = this[this.relevanceID]
            this.$api.add(this.form1, this.apiPath1).then(() => {
              // 重新获取列表
              this.queryList1.curpage = 1
              this.tableList1 = []
              this.getItemList()

              this.dialogFormVisible1 = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 编辑-数据提交
      updateData1() {
        this.$refs['dataForm1'].validate((valid) => {
          if (valid) {
            this.form1[this.relevanceID] = this[this.relevanceID]
            this.$api.edit(this.form1, this.apiPath1).then(response => {
              // 重新获取列表
              this.getItemList()

              this.dialogFormVisible1 = false
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 删除
      handleDelete1(id = 0) {
        let current = this
        let id_str = ''
        if (!id) {
          // 多选
          if (!this.multipleSelection1.length) {
            this.$message({
              message: '请选择删除的条目！',
              type: 'warning'
            })
            return false
          }
          // 数据处理
          this.multipleSelection1.forEach(item => {
            id_str += item[current.keyName1] + ','
          })
        } else {
          id_str = id
        }

        // 提交数据
        this.$confirm('确认删除数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.del({ id_str: id_str }, this.apiPath1).then(response => {
            // 重新获取列表
            this.getItemList()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          })
        })
      },
			// 排序
			updateSort1(id = 0, sort = '') {
				this.$api.editSort({
					id: id,
					sort: sort
				}, this.apiPath1).then(response => {
					this.$message({
						message: '排序成功',
						type: 'success'
					})
				})
			},
			//启用
			handleShow1(id = 0) {
				this.$confirm('确认启用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.show({ id_str: id }, this.apiPath1).then(response => {
						// 重新获取列表
						this.getItemList()
						this.$message({
							message: '启用成功',
							type: 'success'
						})
					})
				})
			},
			//禁用
			handleUpshow1(id = 0) {
				this.$confirm('确认禁用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.upshow({ id_str: id }, this.apiPath1).then(response => {
						// 重新获取列表
						this.getItemList()
						this.$message({
							message: '禁用成功',
							type: 'success'
						})
					})
				})
			}
/*******************************公共方法1END******************************/
		}
	}
</script>
